<template>
  <view class="login-container">
    <image class="logo" src="/static/njt.png"></image>
    <view class="title">
      <u--text align="center" size="40px" text="农检通" type="success"></u--text>
    </view>
    <view class="subtitle">
      <u--text align="center" size="25px" text="食用农产品合格证管理系统" type="success"></u--text>
    </view>

    <u--form ref="uForm" :model="model1" :rules="rules" class="njt-form" labelPosition="left">
      <!-- 用户名输入项 -->
      <u-form-item label="手机号码" labelWidth="auto" prop="username">
        <u--input v-model="model1.username" :clearable="true" border="surround" placeholder="请输入手机号"
                  type="text"></u--input>
      </u-form-item>

      <!-- 密码输入项 -->
      <u-form-item label="输入密码" labelWidth="auto" prop="password">
        <u--input v-model="model1.password" :clearable="true" :show-password="showPassword" border="surround"
                  placeholder="请输入密码" type="password"
                  @click-icon="showPassword = !showPassword"></u--input>
      </u-form-item>

      <!-- 按钮组 -->
      <u-form-item>
        <u-button class="login-btn" text="登录" type="success" @click="submitForm"></u-button>
        <view class="links-container">
          <view class="left">
            <u--text size="15px" text="新用户注册" type="success" @click="gotoRegister"></u--text>
          </view>
          <view class="right">
            <u--text size="15px" text="忘记/修改密码" type="success" @click="gotoModify"></u--text>
          </view>
        </view>
      </u-form-item>
    </u--form>
    <view class="agreement-container">
      <u-checkbox-group v-model="checkboxValue">
        <u-checkbox
            v-for="(item, index) in checkboxList" :key="index"
            :label="item.name"
            :name="item.name"
        ></u-checkbox>
      </u-checkbox-group>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 表单数据模型
      model1: {
        username: '',
        password: ''
      },
      checkboxValue: [],
      checkboxList: [{
        name: '我已阅读并同意《用户协议及隐私政策》',
        disabled: false
      }],
      // 表单验证规则
      rules: {
        username: [{
          required: true,
          message: '请输入手机号',
          trigger: ['blur', 'change']
        },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '请输入正确的手机号格式',
            trigger: ['blur', 'change']
          },
          {
            min: 11,
            max: 11,
            message: '手机号码应为11位',
            trigger: ['blur', 'change']
          }
        ],
        password: [{
          required: true,
          message: '请输入密码',
          trigger: ['blur', 'change']
        },
          {
            min: 6,
            max: 20,
            message: '密码长度在6-20个字符之间',
            trigger: ['blur', 'change']
          }
        ]
      },
      // 密码显示状态
      showPassword: false,
      // 后端API基础地址
      baseUrl: 'http://localhost:8080'
    }
  },
  methods: {
    // 跳转到注册页面
    gotoRegister() {
      uni.navigateTo({
        url: "/pages/njt/register"
      });
    },

    gotoModify() {
      uni.navigateTo({
        url: "/pages/njt/modify"
      });
    },

    // 提交登录表单
    async submitForm() {
      // 检查是否同意协议
      if (this.checkboxValue.length === 0) {
        uni.$u.toast('请阅读并同意用户协议及隐私政策');
        return;
      }

      this.$refs.uForm.validate().then(async (isValid) => {
        if (isValid) {
          try {
            uni.showLoading({
              title: '登录中...',
              mask: true
            });

            // 调用后端登录接口
            uni.request({
              url: `${this.baseUrl}/api/login`,
              method: 'POST',
              data: {
                username: this.model1.username,
                password: this.model1.password
              },
              header: {
                'Content-Type': 'application/json'
              },
              success: (res) => {
                uni.hideLoading();

                if (res.statusCode === 200) {
                  const result = res.data;
                  if (result.code === 200) {
                    // 登录成功，保存token和用户信息
                    uni.setStorageSync('token', result.data.token);
                    uni.setStorageSync('userInfo', result.data.userInfo);

                    uni.$u.toast('登录成功');

                    // 跳转到首页 - 修改为 navigateTo
                    setTimeout(() => {
                      uni.navigateTo({
                        url: '/pages/index/index'
                      });
                    }, 1000);
                  } else {
                    uni.$u.toast(result.msg || '登录失败，请检查账号密码');
                  }
                } else {
                  uni.$u.toast('网络错误，无法连接服务器');
                }
              },
              fail: (err) => {
                uni.hideLoading();
                console.error('登录异常：', err);
                uni.$u.toast('系统异常，请稍后再试');
              }
            });
          } catch (error) {
            uni.hideLoading();
            console.error('登录异常：', error);
            uni.$u.toast('系统异常，请稍后再试');
          }
        }
      }).catch((validateErr) => {
        console.log('表单验证失败：', validateErr);
      });
    }
  }
}
</script>

<style scoped>
.links-container {
  display: flex;
  justify-content: space-between;
  margin-top: 20rpx;
}

.agreement-container {
  margin-top: 40px;
  width: 100%;
  max-width: 500rpx;
}

.title {
  margin-bottom: 10px;
}

.subtitle {
  margin-bottom: 40px;
}

.login-container {
  padding: 30rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.njt-form {
  width: 100%;
  max-width: 500rpx;
  background-color: #ffffff;
  padding: 50rpx 30rpx;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.login-btn {
  width: 100%;
}

.logo {
  height: 200rpx;
  width: 200rpx;
  margin-top: 100rpx;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 20rpx;
}
</style>
